<?php

// # $Id: raw.php 8 2012-01-02 05:09:57Z nickoos85@gmail.com $

function privmsg($who, $data) {

	$privcmdTab = array(
		'help' => 'command_help'
	);

	$pubcmdTab = array(
		'coca' => 'command_coca'
	);


	preg_match("!(.+) :([^ ]+)(.+)!i", $data, $result);
	$result[3] = trim($result[3]);

	if($result[2][0] == CMDCARAC)
		$result[2] = substr($result[2], 1);
 
	if(strtolower($result[1]) == strtolower(NICK)) {
		foreach( $privcmdTab as $tCmd=>$test) {
			if(strtolower($result[2]) == $tCmd) {
				call_user_func(strtolower($test), &$who, strtolower(&$result[3]));
			}
		}
	} else {
		foreach( $pubcmdTab as $tCmd=>$test) {
			if(strtolower($result[2]) == $tCmd) {
				call_user_func(strtolower($test), &$who, &$result[1], strtolower(&$result[3]));
			}
		}
	}

    if(!isset($result[3]))
        $result[3] = NULL;
 
    //echo 'who['.$who.']'.' chan ['.$result[1].'] cmd['.$result[2].']'.' reste['.$result[3].']'."\n";
 
}

function parser(&$data) {
    $cmdTab = array('PING' => 'ping', 422 => 'endCnx', 376 => 'endCnx', 'PRIVMSG' => 'privmsg');
 
 
 
    if( $data[0] == "\r" || $data[0] == "\n" )
        return;
 
    if(DEBUG == true) echo '<<=['.$data."]\n";
 
    $data[strlen($data)-1] = ''; /*enleve \r*/
 
    if( $data[0] == ':') { /* sous la forme :WHO CMD RESTE*/
        preg_match("!:([^ ]+) ([^ ]+) (.+)!i", $data, $result);
        //var_dump($result);
        $who = $result[1];
        $cmd = $result[2];
 
    } else { /* sous la forme CMD WHO RESTE */
        preg_match("!([^ ]+) ([^ ]+)[^ ](.*)!i", $data, $result);
        $cmd = $result[1];
        $who = $result[2];
    }
 
    //echo 'who['.$who.']'.' cmd['.$cmd.']'.' reste['.$result[3].']'."\n";
 
    if(strchr($who, '!'))
        $who = strstr($who, '!', TRUE);
 
    foreach( $cmdTab as $tCmd=>$test) {
        if($cmd == $tCmd)
            call_user_func($test, &$who, &$result[3]);
    }
 
}

function sendRaw($msg) {
    global $sock;
    if(DEBUG == true) echo '=> '.$msg."\n";
    if( socket_write($sock, $msg."\r\n") === FALSE )
        die('deco');
}

function sendmsg($cible, $msg) {
    sendRaw(':'.NICK.' PRIVMSG '.$cible.' :'.$msg);
}

function ping($who, $reste) {
    sendRaw('PONG '.$who);
}
 
function endCnx($who, $reste) {
    sendRaw(':'.NICK.' JOIN '.CHAN);
}
 
function joinChan($chan) {
    sendRaw(':'.NICK.' JOIN '.$chan);
}

?>